import 'package:http/http.dart' as http;
import 'package:flutterclue/http_util/base_http.dart';
import 'base_http.dart';
import 'dart:convert';
import 'constant_url.dart';
import 'dart:async';
import 'package:crypto/crypto.dart';
import 'package:flutterclue/mvp/mode/base_mode.dart';
import 'package:flutterclue/utils/SharePreferensUtil.dart';

class HttpUtilsByHttp extends HttpInterface {
  static HttpUtilsByHttp _httpUtilsByHttp = new HttpUtilsByHttp();

  static HttpUtilsByHttp initInstance() {
    return _httpUtilsByHttp;
  }

  Future excuteBody(Map<String, Object> params) async {
    String token =
        await SharePreferencesUtil.getString(SharePreferencesUtil.TOKEN);
    if (token != null && token.toString().isNotEmpty) {
      params["Token"] = token.toString();
    }
    params["LoginType"] = "Android";
    Map<String, String> paramsBody = new Map();
    params.forEach((key, value) {
      paramsBody[key] = value;
    });
    params["KeyCode"] = ApiUrl.KeyCode;
    paramsBody["Version"] = "1.0.0";
    paramsBody["SecCode"] = encryption(sortStringArray(params));
    return paramsBody;
  }

  ///参数排序
  List<String> sortStringArray(Map<String, Object> hm) {
    List<String> list = new List();
    hm.forEach((key, value) {
      String content = key + "=" + value + "&";
      list.add(content);
    });
    list.sort((a, b) => a.toUpperCase().compareTo(b.toUpperCase()));
    return list;
  }

  ///参数MD5
  String encryption(List<String> list) {
    StringBuffer plainText = new StringBuffer();
    list.forEach((value) {
      plainText.write(value);
    });
    var content = new Utf8Encoder()
        .convert(plainText.toString().substring(0, plainText.length - 1));
    Digest digest = md5.convert(content);
    List<int> list1 = digest.bytes;
    StringBuffer buf = new StringBuffer();
    list1.forEach((digest) {
      if (digest < 0) digest += 256;
      if (digest < 16) buf.write("0");
      buf.write(digest.toInt().toRadixString(16));
    });
    return buf.toString();
  }

  @override
  Future<BaseBean> get(
      {String url,
      Map<String, Object> headers,
      Map<String, Object> params,
      onSelect}) {
    // TODO: implement get
    return null;
  }

  @override
  Future<BaseBean> post(
      {String url,
      Map<String, Object> headers,
      Map<String, Object> params,
      onSelect}) async {
    var response = await http
        .post(ApiUrl.BASE_DEBUG_URL + url, body: excuteBody(params))
        .catchError((error) {
      onSelect(error.toString());
    });
    var jsonString = json.decode(response.body.toString());
    BaseBean baseBean = BaseBean.fromParams();
    baseBean.Message = jsonString["Message"];
    baseBean.Code = jsonString["Code"];
    baseBean.Data = jsonString["Data"];
    return baseBean;
  }
}
